package com.samsung.spen.sshare.main.data;

import java.util.ArrayList;

import com.samsung.spen.sshare.main.sms.SMSReceiver;

import android.app.Activity;
import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class SshareDataService extends Service implements HistoryColumns,
		RequestSMSColumns, CommunicationLogColumns {

	SshareDataServiceBinder mBinder = new SshareDataServiceBinder();
	DataHelper mDataHelper = new DataHelper(this);

	public class SshareDataServiceBinder extends Binder {
		public SshareDataService getService() {
			return SshareDataService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if(intent.getAction().equals("SMS_RECEIVER_INSERT"))
		{
			this.insertSMS(intent.getStringExtra(SMSReceiver.PHONE), 
					intent.getLongExtra(SMSReceiver.TIME, 0), 
					intent.getStringExtra(SMSReceiver.CONTENT), 
					intent.getStringExtra(SMSReceiver.IP));
		}
	}
	
	public History getHistoryByID(int _id) {
		History history = null;

		Cursor cursor = this.query(HISTORY_TABLE_NAME, null, HistoryColumns._ID
				+ "= ?", new String[] { _id + "" }, null, null, null);
		if (cursor.moveToFirst()) {
			history = getHistoryFromCursor(cursor);
		}
		return history;
	}

	public ArrayList<CommunicationLog> getCLogFromHistory() {
		ArrayList<CommunicationLog> logs = new ArrayList<CommunicationLog>();
		Cursor cursor = this.query(COMMUNICATION_LOG_TABLE_NAME, null, null,
				null, null, null,
				CommunicationLogColumns.LAST_COMMUNICATION_TIME + " DESC");
		if (cursor.moveToFirst()) {
			do {
				long id = cursor.getLong(cursor
						.getColumnIndex(CommunicationLogColumns._ID));
				String phone = cursor.getString(cursor
						.getColumnIndex(CommunicationLogColumns.PHONE_NUMBER));
				long lastCommunication = cursor
						.getLong(cursor
								.getColumnIndex(CommunicationLogColumns.LAST_COMMUNICATION_TIME));
				CommunicationLog cLog = new CommunicationLog(id, phone,
						lastCommunication);
				logs.add(cLog);
			} while (cursor.moveToNext());
		}
		return logs;
	}

	public String getPhoneHistoryByPhone(String phone) {
		String phoneTime = "";
		Cursor cursor = this.query(COMMUNICATION_LOG_TABLE_NAME, null,
				CommunicationLogColumns.PHONE_NUMBER + "= ?",
				new String[] { phone }, null, null, null);
		if (cursor.moveToFirst()) {
			long lastCommunication = cursor
					.getLong(cursor
							.getColumnIndex(CommunicationLogColumns.LAST_COMMUNICATION_TIME));
			phoneTime = phone + "#" + lastCommunication;
		}
		return phoneTime;
	}
	
	public ArrayList<History> getHistoryWithPhone() {
		ArrayList<History> histories = new ArrayList<History>();
		Cursor cursor = this.query(HISTORY_TABLE_NAME, null, null, null, 
				HistoryColumns.PHONE_NUMBER, null, HistoryColumns.DATE_TIME + " DESC");
		if (cursor.moveToFirst()) {
			do {
				History history = getHistoryFromCursor(cursor);
				histories.add(history);
			} while (cursor.moveToNext());
		}
		return histories;
	}

	public ArrayList<History> getHistoryListByPhone(String phone) {
		ArrayList<History> histories = new ArrayList<History>();
		Cursor cursor = this.query(HISTORY_TABLE_NAME, null,
				HistoryColumns.PHONE_NUMBER + "= ?", new String[] { phone },
				null, null, null);
		if (cursor.moveToFirst()) {
			do {
				History history = getHistoryFromCursor(cursor);
				histories.add(history);
			} while (cursor.moveToNext());
		}
		return histories;
	}
	
	public String getPhoneNumberFromIP(String ip){
		ArrayList<RequestSMS> requests = new ArrayList<RequestSMS>();
		Cursor cursor = this.query(REQUEST_SMS_TABLE_NAME, new String[] {RequestSMSColumns.PHONE_NUMBER}, 
				RequestSMSColumns.IP + " = ?", new String[] {ip} , null, null, RequestSMSColumns.DATE_TIME + " DESC");
		String phoneNum = "no contact";
		if(cursor.moveToFirst()){
			phoneNum = cursor.getString(cursor.getColumnIndex(RequestSMSColumns.PHONE_NUMBER));
		}
		return phoneNum;
	}

	public long insertHistory(String phoneNum, String ip, String fileName,
			String filePath, long size, long dateTime, int status) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(HistoryColumns.PHONE_NUMBER, phoneNum);
		contentValues.put(HistoryColumns.IP, ip);
		contentValues.put(FILE_NAME, fileName);
		contentValues.put(FILE_PATH, filePath);
		contentValues.put(SIZE, size);
		contentValues.put(HistoryColumns.DATE_TIME, dateTime);
		contentValues.put(STATUS, status);
		long id = this.insert(HISTORY_TABLE_NAME, contentValues);
		String phoneTime = getPhoneHistoryByPhone(phoneNum);

		// update Communication Log table
		if (phoneTime.equals("")) {
			ContentValues values = new ContentValues();
			values.put(CommunicationLogColumns.PHONE_NUMBER, phoneNum);
			values.put(CommunicationLogColumns.LAST_COMMUNICATION_TIME,
					dateTime);
			this.insert(COMMUNICATION_LOG_TABLE_NAME, values);
		} else {
			ContentValues values = new ContentValues();
			values.put(CommunicationLogColumns.LAST_COMMUNICATION_TIME,
					dateTime);
			this.update(COMMUNICATION_LOG_TABLE_NAME, values,
					CommunicationLogColumns.PHONE_NUMBER + "= ?",
					new String[] { phoneNum });
		}
		return id;
	}

	public long insertSMS(String phoneNumber, long dateTime, String content,
			String ip) {
		ContentValues contentValues = new ContentValues();
		contentValues.put(RequestSMSColumns.PHONE_NUMBER, phoneNumber);
		contentValues.put(RequestSMSColumns.DATE_TIME, dateTime);
		contentValues.put(RequestSMSColumns.CONTENT, content);
		contentValues.put(RequestSMSColumns.IP, ip);
		long id = this.insert(REQUEST_SMS_TABLE_NAME, contentValues);
		Log.v(this.getClass().toString(), "insertSMS id: " + id);
		return id;
	}
	

	public int deleteHistoryByPhone(String phone) {
		// delete from Communication Log table
		this.delete(COMMUNICATION_LOG_TABLE_NAME, HistoryColumns.PHONE_NUMBER
				+ "= ?", new String[] { phone });
		// delete from History table
		return this.delete(HISTORY_TABLE_NAME, HistoryColumns.PHONE_NUMBER
				+ "= ?", new String[] { phone });
	}
	
	public int deleteDetailHistory(String phone) {
		return this.delete(HISTORY_TABLE_NAME, HistoryColumns.PHONE_NUMBER + "= ?",
				new String[] {phone });
	}

	public int deleteHistory(long _id) {
		return this.delete(HISTORY_TABLE_NAME, HistoryColumns._ID + "= ?",
				new String[] { _id + "" });
	}

	public int deleteAllHistory() {
		return delete(HISTORY_TABLE_NAME, null, null);
	}

	public ArrayList<RequestSMS> getRequestSMSList() {
		ArrayList<RequestSMS> requests = new ArrayList<RequestSMS>();
		Activity a = new Activity();
		Cursor cursor = this.query(REQUEST_SMS_TABLE_NAME, null, null, null,
				null, null, RequestSMSColumns.DATE_TIME + " DESC");
		if (cursor.moveToFirst()) {
			do {
				RequestSMS request = getRequestSMSFromCursor(cursor);
				requests.add(request);
			} while (cursor.moveToNext());
		}
		return requests;
	}

	public int deleteRequestSMS(long _id) {
		int result = this.delete(REQUEST_SMS_TABLE_NAME, RequestSMSColumns._ID
				+ "= ?", new String[] { _id + "" });
		Log.v(this.getClass().toString(), "delete id: " + _id + " result: "+ result);
		return result;
	}

	public int deleteAllRequestSMS() {
		return this.delete(REQUEST_SMS_TABLE_NAME, null, null);
	}

	public History getHistoryFromCursor(Cursor cursor) {
		History history = null;
		long id = cursor.getLong(cursor.getColumnIndex(HistoryColumns._ID));
		String phoneNumber = cursor.getString(cursor
				.getColumnIndex(HistoryColumns.PHONE_NUMBER));
		String ip = cursor.getString(cursor.getColumnIndex(HistoryColumns.IP));
		String fileName = cursor.getString(cursor.getColumnIndex(FILE_NAME));
		String filePath = cursor.getString(cursor.getColumnIndex(FILE_PATH));
		long size = cursor.getLong(cursor.getColumnIndex(SIZE));
		long dateTime = cursor.getLong(cursor
				.getColumnIndex(HistoryColumns.DATE_TIME));
		int status = cursor.getInt(cursor.getColumnIndex(STATUS));
		history = new History(id, phoneNumber, ip, fileName, filePath, size,
				dateTime, status);
		return history;
	}

	public RequestSMS getRequestSMSFromCursor(Cursor cursor) {
		RequestSMS rSMS = null;
		long id = cursor.getLong(cursor.getColumnIndex(RequestSMSColumns._ID));
		String phoneNumber = cursor.getString(cursor
				.getColumnIndex(RequestSMSColumns.PHONE_NUMBER));
		long dateTime = cursor.getLong(cursor
				.getColumnIndex(RequestSMSColumns.DATE_TIME));
		String content = cursor.getString(cursor.getColumnIndex(CONTENT));
		String ip = cursor.getString(cursor
				.getColumnIndex(RequestSMSColumns.IP));
		int status = cursor.getInt(cursor.getColumnIndex(RequestSMSColumns.SMS_STATUS));
		rSMS = new RequestSMS(id, phoneNumber, dateTime, content, ip, status);
		return rSMS;
	}
	
	public int updateSMSStatus(int status, long id){
		ContentValues values = new ContentValues();
		values.put(RequestSMSColumns.SMS_STATUS, status);
		int result = this.update(REQUEST_SMS_TABLE_NAME, values, 
				RequestSMSColumns._ID + " = ?", new String[] {id+""});
		return result;
	}

	private Cursor query(String table, String[] columns, String selection,
			String[] selectionArgs, String groupBy, String having,
			String sortOrder) {
		SQLiteDatabase sqliteDB = mDataHelper.getReadableDatabase();
		Cursor cursor = sqliteDB.query(table, columns, selection,
				selectionArgs, groupBy, having, sortOrder);
		return cursor;
	}

	private long insert(String table, ContentValues values) {
		SQLiteDatabase sqliteDB = mDataHelper.getWritableDatabase();
		long _id = sqliteDB.insert(table, null, values);
		return _id;
	}

	private int update(String table, ContentValues values, String whereClause,
			String[] whereArgs) {
		SQLiteDatabase sqLiteDB = mDataHelper.getWritableDatabase();
		int result = sqLiteDB.update(table, values, whereClause, whereArgs);
		return result;
	}

	private int delete(String table, String selection, String[] selectionArgs) {
		SQLiteDatabase sqliteDB = mDataHelper.getWritableDatabase();
		int result = sqliteDB.delete(table, selection, selectionArgs);
		return result;
	}
}
